<script setup lang="ts">
import { useTokenStore } from '../stores/counter.ts'
import { useRouter } from "vue-router"
import { login } from '../config/api'
import { ElMessage } from 'element-plus'
import { reactive } from 'vue';
import { ref } from 'vue'
import type { FormInstance, FormRules } from "element-plus";
// import  AxiosResponse  from 'axios'
let ruleForm = reactive({
  phone: '1',
  password: '1'
});

let rules = reactive<FormRules>({
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { min: 1, max: 11, message: '长度在 1 到 11 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码码', trigger: 'blur' },
    { min: 1, max: 11, message: '长度在 1 到 11 个字符', trigger: 'blur' }
  ]
})
let ruleFormRef = ref<FormInstance>(null)

const store = useTokenStore();
const router = useRouter();
const loginHandler = async (formRef: FormInstance) => {
  if (!formRef) return;
  await formRef.validate((valid: boolean) => {
    if (valid) {
      login({ ...ruleForm }).then(res => {
        if (res.code === 200) {
          store.$patch({
            token: res.data.Authorization,
            userInfo: res.data.admin
          })
          sessionStorage.token = res.data.Authorization
          sessionStorage.userInfo = JSON.stringify(res.data.admin)
          router.push("/home")
          ElMessage({
            type: 'success',
            message: '登录成功'
          })
        } else {
          ElMessage({
            type: 'error',
            message: '登录失败'
          })
        }
      })

    } else {
      ElMessage({
        type: 'error',
        message: '验证失败'
      })
    }
  })
}
const resetForm = (formRef: undefined | FormInstance) => {
  if (!formRef) return;
  console.log(111); // ref="ruleFormRef"，不是：ref="ruleFormRef"

  formRef.resetFields() // 重置该表单项，将其值重置为初始值，并移除校验结果
}
</script>
<template>
  <el-container>
    <el-main>
      <el-row>
        <el-col>
          <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="ruleForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loginHandler(ruleFormRef)">立即创建</el-button>
              <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<style>
@media (min-width: 1024px) {
  .about {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
</style>
